 
// const { getInfoFromServer, URLADDRESS } = require('./utils/NetUtils');
// const { refreshLoginInfo } = require('./utils/LoginUtils');
// const LayaMeServerCode = require('./layame/server/ServerCode.json');
function changeLayaMeProId() {
    showChangeLayameProId();
}

function showChangeLayameProId()
{
    var loaderEle;
    let propath = codeMain.getWorkspaceRootPath(); 
    let fs = codeMain.fs;
    let path = codeMain.path;
    let layameFolder = path.join(propath, ".laya", "layame");
 
    let accountInfoPath = path.join(layameFolder, "account.info");
    if(showChangeLayameProId.prototype.layaPackage){
        codeMain.addPopLayer(showChangeLayameProId.prototype.layaPackage);
  
        if (fs.existsSync(accountInfoPath)) { 
            let accountInfoStr = fs.readFileSync(accountInfoPath, "utf8");
            let accountInfo  = JSON.parse(accountInfoStr);
            let currUsername = sessionStorage.getItem("username");
            if (accountInfo.gameId) {
                showChangeLayameProId.prototype.layaMeGameID.value  = accountInfo.gameId;
            }
        }
        return;
    }
    var dialog = electron.remote.dialog;
    var currentSelectedLi = "";
    var _layaProType = 1;
    //创建背景容器
    var layaLayerPop = getElement("div", "layaLayerPop");
    layaLayerPop.style.zIndex = 199999999
    // document.body.appendChild(layaLayerPop);
    codeMain.addPopLayer(layaLayerPop);
    //创建背景
    var layerBackground = getElement("div", "layerBackground");
    layaLayerPop.appendChild(layerBackground);
    var newProTitle = getElement("div", "common-tool-title");
    newProTitle.innerHTML = `
        <div class="common-tool-icon-wrapper">
            <img class="common-tool-icon" title="${codeMain.getPanelLang(625)}" src="skins/default/image/ide/layamaker-newpro.png" style="width: 18px; height: 20px;">
        </div>
        <div class="common-tool-title-content">${codeMain.getPanelLang(625)}</div>
        <div class="common-tool-close"></div>
    `;
    layerBackground.appendChild(newProTitle); 
    layerBackground.style = ` 
    height: 200px;
    width: 400px;
    margin-top: 80px;
    `;
    newProTitle.getElementsByClassName("common-tool-close")[0].onclick = function() {
        codeMain.removePopLayer(layaLayerPop);
    }
    __Layadrag(layaLayerPop, newProTitle)
 

    showChangeLayameProId.prototype.layaPackage = layaLayerPop;   
     //----------右边容器
    var layerBackgroundrightPanel = getElement("div", "layerBackgroundrightPanel");
    layerBackground.appendChild(layerBackgroundrightPanel);

    layerBackgroundrightPanel.style = `
    width: 400px;
    height: 200px; 
    top: 0px;
    left: 0px;
    `; 
     
    ////---------------------------LayaMe
    var layaNewProInput = getElement("div", "layaNewProInput");
    layaNewProInput.style = "margin-top: 20px; ";
    layerBackgroundrightPanel.appendChild(layaNewProInput);
    var input = getElement("span");
    input.style = `
    left: 30`;
    input.innerHTML = `${codeMain.getPanelLang(618)}`; // 游戏ID
    layaNewProInput.appendChild(input);
    
    layaNewProInput.style = `
    width: 400px;
    height: 200px; 
    top: 60px;
    left: 0px;`;
    var layaMeGameID = getElement("input");
    layaMeGameID.value =  "";
    layaNewProInput.appendChild(layaMeGameID);
    
    layaMeGameID.style = `
    width: 216px; 
    top: 0px;`;

    var changBtn = getElement("Button", "refreshBtnLeft");
    layerBackgroundrightPanel.appendChild(changBtn);
    changBtn.style = `
    left: 150px;
    top: 138px;`;
    changBtn.innerHTML = codeMain.getPanelLang(23);//"浏览器打开";
    changBtn.onclick = function()
    { 
        checklayaMeGameID();
        changBtn.blur();
    }

    if (fs.existsSync(accountInfoPath)) {

        let accountInfoStr = fs.readFileSync(accountInfoPath, "utf8");
        let accountInfo  = JSON.parse(accountInfoStr);
        let currUsername = sessionStorage.getItem("username");
        if (accountInfo.gameId) {
            layaMeGameID.value  = accountInfo.gameId;
        }
    } else {
         
    }
    showChangeLayameProId.prototype.layaMeGameID = layaMeGameID;
    function checklayaMeGameID() {
        // let isGo = true;
        let gameid = layaMeGameID.value;
        if (!gameid) {
            alert("LayaMe gameid不可为空，请填写LayaMe gameid");
            return;
        }

        refreshLoginInfo().then(() => {
            // 绑定gameid
            let loginInfo = codeMain.layaPageIns.getLoginInfo();
            let infoObj = {
                url: `${URLADDRESS.layame}/ide/idebindgame?ide_token=${loginInfo.token_master}&game_id=${gameid}`,
                openMethod: "GET",
                sendContent: null
            };
            return getInfoFromServer(infoObj)
        }).then((res) => {
            // 查询绑定
            let resObj = JSON.parse(res);
            let 
                ret = resObj.ret,
                msg = resObj.msg,
                data = resObj.data;
            // 请求成功了，检查是否绑定
            if (ret === 0) {
                verifyAgreeAsso(gameid, (agreeResObj) => {
                    document.body.removeChild(loaderEle);
                    let status = agreeResObj && agreeResObj.data && agreeResObj.data.status;
                    if (status === "1") { // 同意绑定的情况 
                        // layame项目，存储账号相关信息  
                        if (fs.existsSync(accountInfoPath)) {

                            fs.writeFileSync(accountInfoPath, JSON.stringify({
                                username: sessionStorage.getItem("username"),
                                gameId: gameid }), "utf8");
                                
                                alert(agreeResObj.msg || "绑定成功");
                                codeMain.removePopLayer(layaLayerPop);
                            
                        } else { 
                            alert("找不到.laya/layame/account.info");

                        }
                        return;
                    } 
                    if (status === "-1") { // 拒绝的情况
                        alert(agreeResObj.msg || "绑定请求被拒绝，请确认gameid或与管理员联系!");
                        return;
                    }
                    let serverMsg = LayaMeServerCode[ret];
                    alert(serverMsg || agreeResObj.msg || "查询绑定关系时出错了，请与服务提供商联系");
                });
                return;
            }
            let serverMsg = LayaMeServerCode[ret];
            alert(serverMsg || msg || "绑定游戏时出错了，请与服务提供商联系");
            document.body.removeChild(loaderEle);
        }).catch((err) => {
            console.error(err);
            alert("绑定游戏时出错了，请与服务提供商联系");
            document.body.removeChild(loaderEle);
        });
        // 添加loading效果
        loaderEle = document.createElement("div");
        loaderEle.id = "loader";
        loaderEle.style.display = "flex";
        loaderEle.style.zIndex = "9999999999";
        loaderEle.innerHTML = `
            <div class="load-container load4">
                <div class="loader">Loading...</div>
            </div>
        `;
        document.body.appendChild(loaderEle);
    }

    // 请求服务器，查看用户是否同意了请求
    function verifyAgreeAsso(gameid, reFunc) {
        let loginInfo = codeMain.layaPageIns.getLoginInfo();
        let infoObj = {
            url: `${URLADDRESS.layame}/ide/getbindstatus?ide_token=${loginInfo.token_master}&game_id=${gameid}`,
            openMethod: "GET",
            sendContent: null
        };
        getInfoFromServer(infoObj).then((res) => {
            let resObj = JSON.parse(res);
            let status = resObj && resObj.data && resObj.data.status;
            if (resObj.ret === 0) { // 用户尚未确认消息
                if (status === "1" || status === "-1") { // 用户同意了 / 用户拒绝了
                    reFunc(resObj);
                    return;
                }
                if (status === "0") {
                    reFunc({
                        msg: "项目ID未绑定，请前往LayaMe帐号后台同意绑定后，再绑定"
                    });
                    
                    // setTimeout(() => { // 延时3s，避免频繁请求
                    //     verifyAgreeAsso(gameid, reFunc);
                    // }, 3000);
                    return;
                }
            }
            reFunc(resObj);
        }).catch((err) => {
            console.error(err);
            reFunc({});
        })
    }
}
 